<template>
  <div>
    <!-- m面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-button type="primary" @click="addCateories">添加分类</el-button>
      <tree-table
        :class="['tree_top']"
        :data="categoriesData"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 通过自定义作用域插槽设置有效列   是否有效区域， 设置对应的模板列： slot="isok"(与columns中设置的template一致) -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 自定义模板列实现级别 -->
        <template slot="isok1" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 自定义模板实现操作 -->
        <template slot="isok2" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editcategories(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removecate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[5, 7, 9, 15]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 这是添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="adddialogVisible"
        width="50%"
        @close="closeAdd"
      >
        <!-- 内容区域 -->
        <el-form
          :model="addForm"
          :rules="addrules"
          ref="addruleForms"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 分类名称 -->
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <!-- 父级分类名称 -->
          <el-form-item label="父级分类" class="col_pore">
            <!-- 级联选择器 -->
            <el-cascader
              v-model="selectkeys"
              :options="cate_get_sencond"
              expandTrigger="hover"
              :props="cascaderProps"
              @change="handleChangekey"
              :class="['cascader']"
              clearable
              change-on-select
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="removecategories">取 消</el-button>
          <el-button type="primary" @click="putcategories">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类对话框 -->
      <el-dialog title="编辑分类" :visible.sync="editdialogVisible" width="50%">
        <!-- 表单 -->
        <el-form
          :model="editForm"
          :rules="addrules"
          ref="editruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editsubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoriesData: [],
      cate_list: [],
      cate_get_sencond: [],
      selectkeys: '',
      // 级联选择器配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      editdialogVisible: false,
      edit_id: '',
      // 修改分类
      editForm: {
        cat_name: ''
      },
      // 用来保存当前查询到商品列表的条数
      total: 0,
      adddialogVisible: false,
      queryinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //  treeTable
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        // type 表示zi定义插槽 template 表示当前使用的模板名称
        { label: '是否有效', prop: '', type: 'template', template: 'isok' },
        { label: '排序', type: 'template', template: 'isok1' },
        { label: '操作', type: 'template', template: 'isok2' }
      ],
      addForm: {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      },
      // 表达验证规则
      addrules: {
        cat_name: [
          { required: true, message: '请输入分类的名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    async getlist() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryinfo
      })
      //   console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      //   console.log(res)
      //  this.cate_list = res.data
      this.categoriesData = res.data.result
      this.cate_list = res.data.result
      this.total = res.data.total
    },
    // 监听当前页显示的条数改变
    handleSizeChange(newPage) {
      // 当用户选中当前要展示条数的结果赋值给参数，重新发起请求
      this.queryinfo.pagesize = newPage
      this.getlist()
    },
    // 监听页码的改变
    handleCurrentChange(newPage) {
      this.queryinfo.pagenum = newPage
      this.getlist()
    },
    // 添加分类
    addCateories() {
      this.gettwolist()
      this.adddialogVisible = true
    },
    // 获取二级分类数据
    async gettwolist() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      //   console.log(res)
      this.cate_get_sencond = res.data
    },
    // 这是级联选择器选择时触发的事件
    handleChangekey() {
      //   console.log(this.selectkeys)
      if (this.selectkeys.length > 0) {
        this.addForm.cat_pid = this.selectkeys.length - 1
        this.addForm.cat_level = this.selectkeys.length
      } else {
        this.addForm.cat_level = this.selectkeys.length
      }
    },
    // 点击添加按钮提交参数
    async putcategories() {
      // 进行与验证
      this.$refs.addruleForms.validate(async (err) => {
        if (!err) return this.$message.error('请输入正确的分类')
      })

      //   console.log(this.addForm.cat_pid)
      const { data: res } = await this.$http.post('categories', this.addForm)
      //   console.log(res)
      if (res.meta.status !== 201) {
        return
        //   this.$message.error('创建失败')
      }
      this.$message.success('创建成功')
      this.getlist()
      this.adddialogVisible = false
      this.addForm.cat_name = ''
    },
    // 点击取消清除所有的内容
    removecategories() {
      this.$refs.addruleForms.resetFields()
      this.addForm = {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      }
    },
    // 关闭dialog对话框
    closeAdd() {
      this.$refs.addruleForms.resetFields()
      this.addForm = {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      }
    },
    // 编辑分类
    async editcategories(id) {
      //   console.log(id)
      this.edit_id = id.cat_id
      this.editdialogVisible = true
      // 实现获取当前分类
      const { data: res } = await this.$http.get(`categories/${id.cat_id}`)
      //   console.log(res)
      this.editForm.cat_name = res.data.cat_name
    },
    async editsubmit() {
      // 进行表单的预验证
      this.$refs.editruleForm.validate(async (validate) => {
        if (!validate) return this.$message.error('请输入分类名称')
      })
      // 发送请求
      const { data: res } = await this.$http.put(
        `categories/${this.edit_id}`,
        this.editForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改分类失败')
      }
      //   console.log(res)
      this.getlist()
      this.editdialogVisible = false
      this.$message.success('修改分类成功')
    },
    // 删除分类
    async removecate(info) {
      // 弹框提醒是否真的删除
      const Result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (Result !== 'confirm') {
        this.$message.info('已经取消了删除')
      }
      // 确定删除
      //   console.log(id)
      this.editForm.cat_name = info.cat_name
      const { data: res } = await this.$http.put(
        `categories/${info.cat_id}`,
        this.editForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      console.log(res)
      this.getlist()
      //   info.children = res.data
      this.$message.success('删除成功')
    }
  }
}
</script>

<style lang="less" scoped>
.tree_top {
  margin-top: 15px !important;
}
.cascader {
  width: 100%;
}
.col_pore {
  position: relative;
}
// .el-cascader {
//   top: 233px !important;
// }
</style>